package com.learn.redis.lock;


import com.learn.redis.config.ServiceInitConfiguration;
import com.learn.redis.lock.impl.FairLockServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author PC
 * 锁工厂类
 */
@Component
public class LockServiceFactory {
    private final static Logger LOGGER = LoggerFactory.getLogger(LockServiceFactory.class);

    private ServiceInitConfiguration serviceInitConfiguration;

    @Autowired
    public void setServiceInitConfiguration(ServiceInitConfiguration serviceInitConfiguration) {
        this.serviceInitConfiguration = serviceInitConfiguration;
    }

    /**
     * 通过锁类型获取lockService
     *
     * @param type 锁类型
     * @return 对应锁类型的lockService
     */
    public LockService getLockServiceByType(String type) {
        LockService lockService = serviceInitConfiguration.getLockServiceMap().get(type);
        if (Objects.isNull(lockService)) {
            LOGGER.error("there is no lockService for the currentType, use fairLockService");
            //TODO 默认使用公平锁，此部分后续可以开一个配置属性，决定找不到的时候使用公平锁还是报错
            return new FairLockServiceImpl();
        }
        return lockService;
    }
}
